package solutions.ferpa.ztest.intf;

import br.com.telescope.adsrt.dom.*;
import br.com.telescope.adsrt.lib.*;
import br.com.telescope.auth.Session;
import br.com.telescope.auth.User;
import br.com.telescope.t2.ServiceModel;
import br.com.telescope.t2.SessionsManager;
import br.com.telescope.t2.exception.ApplicationRuntimeException;
import br.com.telescope.t2.feature.CustomActionFeature;
import br.com.telescope.t2.feature.CustomFeature;
import br.com.telescope.t2.log.LogMessage;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import solutions.ferpa.ztest.ent.*;

/**
 * Sessões ativas.
 * <p>
 * null
 * <P>
 * Telescope origin: RTAUTH_UTIL.LST_SESSIONS
 * <P>
 * @author TELESCOPE - Build task T2 Web Interface Generator
 * <P>
 * @version 0.1
 */
public class LstSessions extends ServiceModel {
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    public static final String GLOBAL_NAME = "RTAUTH_UTIL.LST_SESSIONS";
    
    @Override
    public String globalName() {
        return GLOBAL_NAME;
    }
    
    {
        setTitle("Sessões ativas");
    }
    
    
    // Record items
    
    // Query items
    
    @Override
    public void initAttributes() {
        
    }
    
    @Override
    public String getDefaultOrderBy() {
        return "";
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="LIST">
    public class FList extends CustomActionFeature {
        
        @Override
        public void initForm() {
        }
        
        @Override
        public void onAction() {
            addSubmit(getFeature("LIST")).label("Refresh");
        }
        
        @Override
        public void execute() {
            try {
                list();
            } catch (AdsException ex) {
                throw new ApplicationRuntimeException(ex);
            }
        }
        
        {
            setFeatureName("LIST");
            setTitle("List");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="VIEW">
    public class FView extends CustomFeature {
        
        @Override
        public void initForm() {
        }
        
        @Override
        public void onAction() {
            addSubmit(getFeature("LIST")).label("List");
            addSubmit(getFeature("KILL")).label("Forçar encerramento");
        }
        
        @Override
        public void execute() {
            try {
                view();
            } catch (AdsException ex) {
                throw new ApplicationRuntimeException(ex);
            }
        }
        
        {
            setFeatureName("VIEW");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="KILL">
    public class FKill extends CustomActionFeature {
        
        @Override
        public void initForm() {
        }
        
        @Override
        public void execute() {
            try {
                kill();
            } catch (AdsException ex) {
                throw new ApplicationRuntimeException(ex);
            }
        }
        
        {
            setFeatureName("KILL");
            setTitle("Forçar encerramento");
            setPrimary(false);
        }
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="initFeatures">
    
    @Override
    protected void initFeatures() {
        addFeature(new FList());
        addFeature(new FView());
        addFeature(new FKill());
        super.initFeatures();
    }
    
    @Override
    public String getDefaultFeature() {
        return "LIST";
    }
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="Getters and Setters">
    // </editor-fold>
    
    /**
     * List.
     * <p>
     * Apresenta uma lista das sessões atuais.
     * <P>
     */
    public void list() throws AdsException {
        // <user-code id="840735" parentId="840733" hashcode="-6b0be6f4" length="3089">
        // import br.com.telescope.t2.SessionsManager;
        // import br.com.telescope.t2.log.LogMessage;
        // import java.util.List;
        // import java.util.Date;
        // import br.com.telescope.auth.Session;
        // import java.util.Collection;
        // import java.util.Locale;
        StringBuilder out = new StringBuilder();
        SessionsManager sm = SessionsManager.getInstance();
        Collection<Session> sessions = sm.getSessions().values();
        SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy H:mm:ss", Locale.getDefault());
        for (int i = 0; i < 4; i++) {
            for (Session session : sessions) {
                int k = 0;
                LogMessage log = session.getLogMessage();
                String status;
                String time;
                int size = session.getCurrentThreads().size();
                if (size > 0) {
                    status = "Running (" + size + ")";
                    time = (System.currentTimeMillis() - session.getLastUsedDate().getTime())/1000 + "s";
                } else {
                    time = "";
                    status = "Finished";
                    k += 2;
                }
                User u = (User) session.getObject(Session.USER);
                if (u == null) {
                    k++;
                }
                if (i == k) {
                    String service = session.getAccessedServices().keySet().toString();
                    String loginName = (u != null ? u.getLoginName() : "");
                    Date lastUsed = session.getLastUsedDate();
                    Date expiration = session.getExpirationDate();
                    out.append("<tr>");
                    out.append("<td><a href=\"?Z_ACTION=VIEW&SID=").append(session.getId()).append("\">").append(session.getId()).append("</a></td>");
                    out.append("<td>").append(loginName).append("</td>");
                    out.append("<td>").append(session.getHost()).append("</td>");
                    out.append("<td>").append(fmt.format(session.getCreationDate())).append("</td>");
                    out.append("<td>").append(lastUsed == null ? "" : fmt.format(lastUsed)).append("</td>");
                    out.append("<td>").append(expiration == null ? "" : fmt.format(expiration)).append("</td>");
                    out.append("<td>").append(service).append("</td>");
                    out.append("<td>").append(status).append("</td>");
                    out.append("<td>").append(time).append("</td>");
                    out.append("<td>").append(session.getActiveTime()/1000).append("s</td>");
                    out.append("</tr>");
                }
            }
        }
        ctx.p("<div class=\"table-container\"><table class=\"list\">"
                + "<thead>"
                + "<tr>"
                + "<th>Session ID</th>"
                + "<th>User</th>" 
                + "<th>Host</th>"
                + "<th>Creation Date</th>" 
                + "<th>Last used Date</th>"
                + "<th>Expiration Date</th>"
                + "<th>Service</th>"
                + "<th>Status</th>" 
                + "<th>Time running</th>" 
                + "<th>Acum time</th>" 
                + "</tr></thead><tbody>" 
                + out 
                + "</tbody></table></div>" 
                + "Maximum concurrent sessions: " 
                + sm.getMaxConcurrentSessions()
                + "<br>Maximum concurrent user sessions: " 
                + sm.getMaxConcurrentUserSessions()
                );
        // </user-code>
    }
    
    /**
     * null.
     */
    public void view() throws AdsException {
        // <user-code id="840761" parentId="840754" hashcode="601d9c37" length="2534">
        // import br.com.telescope.adsrt.dom.*;
        
        String sid = ctx.getParameter("SID", "");
        SessionsManager sm = SessionsManager.getInstance();
        Session session = sm.getSessions().get(sid);
        if (session != null) {
            LogMessage log = session.getLogMessage();
            List<Thread> threads = session.getCurrentThreads();
            String status;
            String time;
            if (threads.size() > 0) {
                status = "Running";
                time = (System.currentTimeMillis() - session.getLastUsedDate().getTime())/1000 + "s";
            } else {
                time = "";
                status = "Finished";
            }
            Form form = getForm();
            form.add((new DomText()).name("SESSION").label("Session").value(sid));
            form.add((new DomText()).name("USER").label("User").value(session.getUserName()));
            form.add((new DomText()).name("HOST").label("Host").value(session.getHost()));
            form.add((new DomDateTime()).name("DTCR").label("Creation date").value(session.getCreationDate()));
            form.add((new DomDateTime()).name("DTLU").label("Last used date").value(session.getLastUsedDate()));
            form.add((new DomDateTime()).name("DTED").label("Expiration date").value(session.getExpirationDate()));
            form.add((new DomDateTime()).name("LR").label("Last request").value(log.getStartDate()));
            form.add((new DomText()).name("RQ").label("Request").value(log.getOrigin()));
            form.add((new DomText()).name("PAR").label("Parameters").value(log.getMessage()));
            form.add((new DomText()).name("ST").label("Status").value(status));
            form.add((new DomText()).name("TR").label("Time running").value(time));
            form.add((new DomText()).name("SVCS").label("Services").value(session.getAccessedServices()));
            form.add((new DomText()).name("PROP").label("Properties").value(session.getParametersMap()));
            
            if (threads.size() > 0) {
                for (Thread thread : threads) {
                    StringBuilder stt = new StringBuilder();
                    for (StackTraceElement ste : thread.getStackTrace()) {
                        if (stt.length() > 0) stt.append("\n    ");
                        stt.append(ste.toString());
                    }
                    long tid = thread.getId();
                    form.add((new DomText()).name("THRD" + tid)
                            .label("Thread").value(thread.getId() 
                            + " - " + thread.getName() 
                            + " - " + thread.getState()));
                    form.add((new DomTextLong()).name("STTR" + tid).label("Stack").value(stt));
                }
            }
            
            form.setEditable(false);
        } else {
            list();
        }
        // </user-code>
    }
    
    /**
     * Forçar encerramento.
     * <p>
     * Derruba uma sessão
     */
    public void kill() throws AdsException {
        // <user-code id="840864" parentId="840862" hashcode="653da85a" length="430">
        String sid = ctx.getParameter("A_SESSION");
        SessionsManager sm = SessionsManager.getInstance();
        Session session = sm.getSessions().get(sid);
        for (Thread t : session.getCurrentThreads()) {
            if (t != null) {
                t.interrupt();
                try {
                    Thread.sleep(200);
                } catch (InterruptedException ignore) {
                }
                ctx.showSuccess("Thread " + t.getId() + " interrupted!");
            }
        }
        list();;
        // </user-code>
    }
}
